package com.example.demo.module.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.module.entity.User;
import com.example.demo.module.convert.UserConvert;
import com.example.demo.module.dto.UserDTO;
import com.example.demo.module.mapper.UserMapper;
import com.example.demo.module.service.IUserService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 测试用户 服务实现类
 * </p>
 *
 * @author sk
 * @since 2025-01-15
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    public UserDTO getUserByUserDTO(UserDTO userDTO) {
        User user = this.getBaseMapper().selectById(userDTO.getId());
        return UserConvert.INSTANCE.toDto(user);
    }

    @Cacheable(value = "users", key = "'user_' + #id", unless = "#result == null")
    public User getUserById(String id) {
        // 模拟数据库查询
        return this.getBaseMapper().selectById(id);
    }

    @CachePut(value = "users", key = "#id")
    public void updateUser(String id, String name) {
        // 模拟更新数据库并返回新值
        User user = this.getBaseMapper().selectById(id);
        user.setName(name);
        this.getBaseMapper().updateById(user);
    }

    @CacheEvict(value = "users", key = "#id")
    public void deleteUser(String id) {
        // 模拟删除数据库记录
        System.out.println("User with id " + id + " has been deleted from database and cache.");
        this.getBaseMapper().deleteById(id);
    }

    @CacheEvict(value = "users", allEntries = true)
    public void clearCache() {
        System.out.println("All user cache has been cleared.");
    }

}
